package com.ljh.myaiagent.controller;


import com.ljh.myaiagent.agent.model.MyManus;
import com.ljh.myaiagent.app.LoveApp;
import com.ljh.myaiagent.common.BaseResponse;
import com.ljh.myaiagent.common.ResultUtils;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

@RestController
@RequestMapping("/ai")
public class AiController {
    @Resource
    private LoveApp loveApp;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatModel dashscopeChatModel;

    @GetMapping("/love_app/chat/sync")
    public BaseResponse<String> doChatWithLoveAppSync(String message, String chatId){
        String doChat = loveApp.doChat(message, chatId);
        return ResultUtils.success(doChat);
    }

    // 使用SSE流失接口
    @GetMapping("/love_app/chat/sse")
    public Flux<ServerSentEvent<String>> doChatWithLoveAppSse(String message, String chatId){
        return loveApp.doChatByStream(message, chatId)
                .map(chunk -> ServerSentEvent.<String>builder()
                        .data(chunk).build());
    }

    // 使用SSEEmitter
    @GetMapping("/love_app/chat/sse/emitter")
    public SseEmitter doChatWithLoveAppEmitter(String message, String chatId){
        SseEmitter sseEmitter = new SseEmitter(180000L); // 设置超时时间为3分钟
        loveApp.doChatByStream(message, chatId)
                .subscribe(
                        // 处理每条信息
                        chunk -> {
                            try {
                                sseEmitter.send(chunk);
                            } catch (IOException e) {
                                sseEmitter.completeWithError(e);
                            }
                        },
                        sseEmitter::completeWithError,
                        sseEmitter::complete
                );
        return sseEmitter;
    }

    @GetMapping("/manus/chat")
    public SseEmitter doChatWithManus(String message){
        MyManus myManus = new MyManus(allTools, dashscopeChatModel);
        return myManus.runStream(message);
    }
}
